package com.itheima.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class RecommentMovementJob {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    // 间隔6小时，完成圈子推荐更新
    // @Scheduled(cron = "0/30 * * * * ?")
    public void RecommentMovemenUpdate() {
        System.out.println("推荐动态start");

        // 1.获取所有全推荐动态的key
        Set<String> keys = stringRedisTemplate.keys("QUANZI_PUBLISH_RECOMMEND_*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                // 2.获取推荐用户id
                Long userId = Long.parseLong(key.replaceAll("QUANZI_PUBLISH_RECOMMEND_", ""));
                // 3.获取推荐动态pid
                String value = stringRedisTemplate.opsForValue().get(key);
                // 4.删除原有数据
                stringRedisTemplate.delete(key);
                mongoTemplate.remove(new Query(Criteria.where("userId").is(userId)), RecommendMovement.class);
                // 5.保存最新推荐动态
                // 5-1 获取pid数组
                String[] split = value.split(",");
                // 5-2 遍历pid数组
                for (String pid : split) {
                    // 5-3 查询动态详情
                    Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(Long.parseLong(pid))), Movement.class);

                    // 5-4 封装推荐动态
                    RecommendMovement recommendMovement = new RecommendMovement();
                    recommendMovement.setCreated(System.currentTimeMillis());// 推荐时间
                    recommendMovement.setUserId(userId); // 推荐用户id
                    recommendMovement.setPid(Long.parseLong(pid)); // 动态pid
                    recommendMovement.setPublishId(movement.getId()); // 动态id
                    recommendMovement.setScore(RandomUtil.randomDouble(60, 100)); // 推荐得分

                    // 5-5 保存推荐动态
                    mongoTemplate.save(recommendMovement);

                }
            }
        }
        System.out.println("推荐动态end");

    }
}
